
cc.Class({
    extends: cc.Component,

    properties: {
        blockLayerNode: cc.Node,
        blockPrefab: cc.Prefab,
        baseNodeArr: [cc.Node],
        audioMove: {
              type: cc.AudioClip,
              default: null
          },
        audioScore: {
              type: cc.AudioClip,
              default: null
          },

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        window.game = this;

        this.blockNodeArr = [[], [], []];

        this.blocknum = 3;

        this.initBlock(3);
    },

    start() {

    },

    initBlock(num) {
        if(num>=6){
            num = 6;
        }

        for(let i=0;i<this.blockNodeArr.length;i++){
            let arr=this.blockNodeArr[i];
            for(let j=0;j<arr.length;j++){
                arr[j].destroy();
                cc.audioEngine.playEffect(this.audioScore, false);
            }
        }


        this.blockNodeArr = [[], [], []];

        for (let i = 0; i < num; i++) {
            let blockNode = cc.instantiate(this.blockPrefab);
            this.blockLayerNode.addChild(blockNode);

            blockNode.x = this.baseNodeArr[0].x;
            blockNode.y = -251 + i * 44;

            let blockIndex = num - i - 1

            blockNode.baseIndex = 0;
            blockNode.blockIndex = blockIndex;

            blockNode.getComponent('block').init(blockIndex);

            this.blockNodeArr[0].push(blockNode);
        }
    },

    checkBlock(pos) {
        for (let i = 0; i < this.baseNodeArr.length; i++) {
            let baseNode = this.baseNodeArr[i];
            if (pos.x >= baseNode.x - baseNode.width / 2 && pos.x <= baseNode.x + baseNode.width / 2) {
                return i;
            }
        }
        return -1
    },

    placeBlock(blockNode) {
        let baseIndex = this.checkBlock(blockNode.position);
        if (baseIndex == -1) {
            return false;
        }

        let arr = this.blockNodeArr[baseIndex];
        if (arr.length && arr[arr.length - 1].blockIndex < blockNode.blockIndex) {
            return false;
        }

        if(blockNode.baseIndex == baseIndex){
            return false;
        }

        let baseNode = this.baseNodeArr[baseIndex];
        blockNode.x = baseNode.x;

        this.blockNodeArr[blockNode.baseIndex].pop();
        this.blockNodeArr[baseIndex].push(blockNode);

        blockNode.baseIndex = baseIndex;

        let length = this.blockNodeArr[baseIndex].length;

        blockNode.y = -251 + (length - 1) * 44
        cc.audioEngine.playEffect(this.audioMove, false);

        if(this.blockNodeArr[2].length ==  this.blocknum){
            this.initBlock(++this.blocknum);
            
        }

        return true;
    },
    // update (dt) {},
});
